// Copyright 2010 Google Inc. All Rights Reserved.

package es.us.lsi.aws.api.server;

import java.io.IOException;
import java.security.Principal;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.google.appengine.api.NamespaceManager;
import com.google.appengine.api.users.UserServiceFactory;

public class NamespaceFilter implements Filter {


	@Override
	public void init(FilterConfig config) throws ServletException {
		if (NamespaceManager.get() == null) {
			// Assuming there is a logged in user.
			NamespaceManager.set("");
		}
	}

	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		Principal p = ((HttpServletRequest) request).getUserPrincipal();
		if (p != null) {

				String namespace = UserServiceFactory.getUserService()
						.getCurrentUser().getUserId();
				NamespaceManager.set(namespace);
			
		}

		// chain into the next request
		chain.doFilter(request, response);
	}


	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
}